# 商品信息文件
import hashlib
import os
import random
import time
from datetime import datetime

from django.core.paginator import Paginator
from django.db.models import Q
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from pet_admin.models import Goods, GoodType, Users


def find(request, pageIndex=1):
    """
        查询全部商品信息视图
    """
    goods = Goods.objects  # 实例化User对象
    goods = goods.filter(good_status__lt=9).order_by('good_id')  # 过滤出来状态小于9的数据

    searchKey = []
    # 获取并判断搜索条件
    good_name = request.GET.get("good_name", None)  # 获取表单提交数据
    if good_name:
        goods = goods.filter(good_name__contains=good_name)
        searchKey.append("good_name=" + good_name)

    type_id = request.GET.get("type_id", None)  # 获取表单提交数据
    if type_id:
        goods = goods.filter(type_id=type_id)
        searchKey.append("type_id=" + type_id)

    # 分页处理
    pageIndex = int(pageIndex)
    page = Paginator(goods, 10)  # 每页多少条
    maxPage = page.num_pages  # 获取最大页数
    # 处理页码越界
    if pageIndex > maxPage:
        pageIndex = maxPage
    if pageIndex < 1:
        pageIndex = 1
    goods = page.page(pageIndex)  # 获取当前页数据
    pages = page.page_range  # 获取页码列表信息

    # 遍历当前商品信息并封装对应的商品类型
    for good in goods:
        good_type = GoodType.objects.get(type_id=good.type_id)
        good.type_name = good_type.type_name

        create_user = Users.objects.get(user_id=good.good_createuser)
        good.createUser = create_user.user_name

        update_user = Users.objects.get(user_id=good.good_updateuser)
        good.updateUser = update_user.user_name

    good_type = GoodType.objects.values("type_id", "type_name")

    context = {"goods": goods, "pages": pages, "pageIndex": pageIndex, "maxPage": maxPage,
               "searchKey": searchKey, "good_type": good_type, "type_id": type_id}
    return render(request, 'pet_admin/good_manage/good_info/index.html', context)


def add(request):
    """
        添加商品分类视图
    """
    good_type = GoodType.objects.filter(type_status__lt=9).values("type_id", "type_name")
    context = {"good_type": good_type}
    return render(request, "pet_admin/good_manage/good_info/add.html", context)


def insert(request):
    """
        执行添加程序方法
    """
    try:
        goods = Goods()
        goods.good_name = request.POST["good_name"]
        print(request.POST["type_id"])
        goods.type_id = request.POST["type_id"]
        # 处理商品图片
        good_pic_file = request.FILES.get('good_path', None)
        if not good_pic_file:
            return HttpResponse("没有上传图片")
        good_path = str(time.time()) + "." + good_pic_file.name.split('.').pop()
        destination = open("./static/uploads/goods_path/" + good_path, "wb+")
        for chunk in good_pic_file.chunks():
            destination.write(chunk)
        destination.close()
        goods.good_path = good_path  # 商品图片

        goods.good_price = request.POST["good_price"]  # 单价
        goods.good_hot = request.POST["good_hot"]  # 热销类型
        goods.good_createtime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")  # 商品创建时间
        goods.good_createuser = request.session["adminUser"]["user_id"]  # 取session中的用户ID
        goods.good_updatetime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")  # 商品修改时间
        goods.good_updateuser = request.session["adminUser"]["user_id"]  # 取session中的用户ID
        goods.save()
        context = {"info": "添加成功"}

    except Exception as err:
        print(err)
        context = {"info": "添加失败"}

    return render(request, "pet_admin/info.html", context)


def edit(request, good_id):
    """
        修改商品信息视图
    """
    try:
        good = Goods.objects.get(good_id=good_id)

        good_type = GoodType.objects.values("type_id", "type_name")
        context = {"good": good, "good_type": good_type}

        return render(request, "pet_admin/good_manage/good_info/edit.html", context)
    except Exception as err:
        print(err)
        context = {"info": "没有找到要修改的信息"}
        return render(request, "pet_admin/info.html", context)


def update(request, good_id):
    """
        执行修改程序的方法
    """
    try:
        good = Goods.objects.get(good_id=good_id)
        good.good_name = request.POST["good_name"]
        good.type_id = request.POST["type_id"]
        # 处理商品图片
        # 获取老图片
        old_good_pic_file = request.POST['old_good_path']
        # 获取新传入的图片名称
        good_pic_file = request.FILES.get('good_path', None)
        if not good_pic_file:
            good_path = old_good_pic_file
        else:
            good_path = str(time.time()) + "." + good_pic_file.name.split('.').pop()
            destination = open("./static/uploads/goods_path/" + good_path, "wb+")
            for chunk in good_pic_file.chunks():
                destination.write(chunk)
            destination.close()

        good.good_path = good_path  # 商品图片
        good.good_price = request.POST["good_price"]
        good.good_hot = request.POST["good_hot"]
        good.type_updatetime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")  # 用户修改时间
        good.save()
        context = {"info": "修改成功"}

        # 删除老图片
        if good_pic_file:
            os.remove("./static/uploads/goods_path/" + old_good_pic_file)
    except Exception as err:
        print(err)
        context = {"info": "修改失败"}
        # 删除新图片
        if good_pic_file:
            os.remove("./static/uploads/goods_path/" + good_pic_file)

    return render(request, "pet_admin/info.html", context)


def deluser(request, good_id):
    """
       执行删除程序的方法
    """
    try:
        good = Goods.objects.get(good_id=good_id)
        good.good_status = 9
        good.good_updatetime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        good.save()
        context = {"info": "删除成功"}

    except Exception as err:
        print(err)
        context = {"info": "删除失败"}

    return render(request, "pet_admin/info.html", context)
